Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to get the document inside a field out after "group by" in MongoDB?

The documents I work on are like this:

{
    "id" : "98syf87erfw8n"
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979",
    .
    .
    .
}

This is the query I used:

db.foobar.aggregate([
    { $group : {
        _id : '$yearpublished',
        myItem: { $first: "$$ROOT" }
    }}
])

The final output is in the form:

{
    { "_id" : "1923", "myItem" : {
                            "id" : "98syf87erfw8n",
                            "foo" : { "objectid" : "39", "stuff" : "65" },
                            "yearpublished" : "1979"
                        }
    }, 
    { "_id" : "1453", "myItem" : {
                            "id" : "88888888888",
                            "foo" : { "objectid" : "394", "stuff" : "55" },
                            "yearpublished" : "1453"
                            "author" : "Ravi Kiran"
                        }
    }
};

But I want the output as:

{
    "id" : "98syf87erfw8n",
    "foo" : { "objectid" : "39", "stuff" : "65" },
    "yearpublished" : "1979"
},
{
    "id" : "88888888888",
    "foo" : { "objectid" : "394", "stuff" : "55" },
    "yearpublished" : "1453",
    "author" : "Ravi Kiran"
}

This means I want to get those documents inside the field myItem out. How can I do that?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use $replaceRoot

Play

db.collection.aggregate({
  "$replaceRoot": {
    "newRoot": "$myItem"
  }
})

There are syntax errors in your output.

"id" : 98syf87erfw8n, is invalid.

It should be "id" : "98syf87erfw8n", Note the quotes

There is comma missing after yearPublished in the second object.

over 4 years ago · Santiago Trujillo Relatório

0

One more project stage after the $group can do the job:

{
 $project: {
  yearpublished: "$myItem.yearpublished",
  foo: "$myItem.foo",
  id: "$myItem.id",
  _id: 0
 }
}

playground

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda